<script lang="ts">
    import type { ExDrawNodeInfo } from "$lib/api/board/board_draw";
    import type { NodeProps } from "@xyflow/svelte";
    import NodeWrap from "../common/NodeWrap.svelte";
    import { request } from "$lib/utils/request";
    import { get_user_session } from "$lib/api/user";
    import { drawStore } from "../../store.svelte";
    import { get_issue as atomgit_get_issue } from "$lib/api/git_provider/atomgit/issue";
    import { get_issue as gitcode_get_issue } from "$lib/api/git_provider/gitcode/issue";
    import {
        RefreshCw,
        SquareArrowOutUpRight,
        SquareKanban,
        X,
    } from "lucide-svelte";
    import { openUrl } from "@tauri-apps/plugin-opener";
    import type { Store as ToastStore } from "@zag-js/toast";
    import { getContext } from "svelte";
    import dayjs from "dayjs";
    import { Modal } from "@skeletonlabs/skeleton-svelte";
    import SvelteMarkdown from "svelte-markdown";
    import type { GIT_SERV_TYPE } from "$lib/api/board/board_extdata";
    import  { get as get_extdata, GIT_SERV_ATOMGIT, GIT_SERV_GITCODE } from "$lib/api/board/board_extdata";

    const toast: ToastStore = getContext("toast");

    const props: NodeProps = $props();
    const nodeInfo = $derived(props.data as ExDrawNodeInfo);

    interface IssueInfo {
        servType: GIT_SERV_TYPE;
        issueTitle: string;
        issueContent: string;
        issueState: string;
        createUser: string;
        assignUser: string;
        updateTime: string;
        htmlUrl: string;
    }

    let issueInfo = $state(null as null | IssueInfo);
    let showContent = $state(false);

    async function loadIssueInfo() {
        const sessionId = await get_user_session();
        const gitServRes = await request(
            get_extdata({
                session_id: sessionId,
                board_id: drawStore.boardInfo?.board_id??"",
                ext_data_id:
                    nodeInfo.content.DevelopIssueContent?.git_serv_id ?? "",
            }),
        );
        if (gitServRes.ext_data.basic_info.serv_type.GitServType == GIT_SERV_ATOMGIT) {
            const issueRes = await atomgit_get_issue(
                gitServRes.ext_data.basic_info.access_token,
                nodeInfo.content.DevelopIssueContent?.owner_path ?? "",
                nodeInfo.content.DevelopIssueContent?.repo_path ?? "",
                nodeInfo.content.DevelopIssueContent?.issue_number ?? "",
            );
            issueInfo = {
                servType: GIT_SERV_ATOMGIT,
                issueTitle: issueRes.title,
                issueContent: issueRes.body,
                issueState: issueRes.state,
                createUser: issueRes.user?.login ?? "",
                assignUser: issueRes.assignee?.login ?? "",
                updateTime: issueRes.updated_at ?? "",
                htmlUrl: issueRes.html_url,
            };
        } else if (
            gitServRes.ext_data.basic_info.serv_type.GitServType == GIT_SERV_GITCODE
        ) {
            const issueRes = await gitcode_get_issue(
                gitServRes.ext_data.basic_info.access_token,
                nodeInfo.content.DevelopIssueContent?.owner_path ?? "",
                nodeInfo.content.DevelopIssueContent?.repo_path ?? "",
                nodeInfo.content.DevelopIssueContent?.issue_number ?? "",
            );
            issueInfo = {
                servType: GIT_SERV_GITCODE,
                issueTitle: issueRes.title,
                issueContent: issueRes.body,
                issueState: issueRes.state,
                createUser: issueRes.user?.login ?? "",
                assignUser: issueRes.assignee?.login ?? "",
                updateTime: issueRes.updated_at ?? "",
                htmlUrl: issueRes.html_url,
            };
        }
    }

    loadIssueInfo();
</script>

<NodeWrap nodeProps={props} showBorder showBgColor showResizer>
    {#if issueInfo == null}
        <div
            class="text-error-900-100 flex items-center justify-center w-full h-full"
        >
            议题不存在
        </div>
    {:else}
        <div class="w-full h-full overflow-hidden">
            <div class="flex gap-2 pl-1">
                <SquareKanban />
                {#if issueInfo.servType == GIT_SERV_ATOMGIT}
                    AtomGit议题
                {:else if issueInfo.servType == GIT_SERV_GITCODE}
                    GitCode议题
                {/if}
            </div>
            <div class="p-1">
                <span
                    role="none"
                    class="hover:underline"
                    onclick={() => (showContent = true)}
                    >{issueInfo.issueTitle}</span
                >
                <button
                    type="button"
                    title="刷新"
                    onclick={() =>
                        loadIssueInfo().then(() => {
                            toast.create({
                                title: "成功",
                                description: "刷新议题内容成功！",
                                type: "success",
                            });
                        })}><RefreshCw size={16} /></button
                >
            </div>
            <ul class="p-1 text-wrap break-all">
                <li>状态:&nbsp;{issueInfo.issueState}</li>
                {#if issueInfo.assignUser != ""}
                    <li>负责人:&nbsp;{issueInfo.assignUser}</li>
                {/if}
                <li>创建人:&nbsp;{issueInfo.createUser}</li>
                <li>
                    更新时间:&nbsp;{dayjs(issueInfo.updateTime).format(
                        "YYYY-MM-DD HH:mm",
                    )}
                </li>
            </ul>
        </div>
    {/if}
</NodeWrap>

<div class="absolute -left-[10000px]">
    {#if issueInfo != null && showContent}
        <Modal
            open={true}
            triggerBase="btn preset-tonal"
            contentBase="card bg-surface-200-800 p-4 space-y-4 shadow-xl w-[800px]"
            backdropClasses="backdrop-blur-xs"
            backdropBase="backdrop-none"
            closeOnEscape={false}
            closeOnInteractOutside={false}
            onOpenChange={(ev) => {
                if (!ev.open) {
                    showContent = false;
                }
            }}
        >
            {#snippet content()}
                <header class="flex justify-between">
                    <h4 class="h4 flex gap-2">
                        查看议题详情
                        <button
                            type="button"
                            onclick={() => openUrl(issueInfo?.htmlUrl ?? "")}
                            ><SquareArrowOutUpRight /></button
                        >
                    </h4>
                    <button
                        type="button"
                        class="btn preset-ghost-primary-500"
                        onclick={() => (showContent = false)}
                    >
                        <X />
                    </button>
                </header>
                <main class="max-h-[calc(100vh-400px)] overflow-y-auto">
                    <SvelteMarkdown source={issueInfo?.issueContent ?? ""} />
                </main>
            {/snippet}
        </Modal>
    {/if}
</div>
